/**
 * Description
 *
 * Creation Date 01/11/2017
 * @author Candy
 */
import TopSellersModel from '../models/top-sellers'
import cheerio from 'cheerio'
import superagent from 'superagent'
import eventproxy from 'eventproxy'

const ep = new eventproxy();

class TopSellers {
	constructor(){}
	async getTopSellers(req, res, next) {
		superagent.get('https://www.visiondirect.com.au/')
			.end(async(err, ares) => {
			if (err) {
				console.log(err);
				return;
			}
			try {
				const $ = cheerio.load(ares.text);
				let name ='',
					brand = '',
					id = 0,
					image = '',
					price = '';
				let elements = $('#pro_slider_sunglasses li');
				for (let i = 0; i<elements.length; i++) {
					brand = $(elements[i]).find('.pro_sli_brand').text();
					name = $(elements[i]).find('.pro_sli_name').text();
					price = $(elements[i]).find('.pro_sli_price').text();
					image = $(elements[i]).find('.pro_sli_pic img').attr('src');
					const hadsellerInfo = await TopSellersModel.findOne({product_name: name, product_image: image}, '-_id');
					if(!hadsellerInfo) {
						id += 1;
						await TopSellersModel.create({product_id: id, category: 'sunglasses', brand, product_name: name, price, product_image: image})
					}

				}
				let eyeElements = $('#pro_slider_eyeglasses li');
				for (let i = 0; i < eyeElements.length; i++) {
					brand = $(eyeElements[i]).find('.pro_sli_brand').text();
					name = $(eyeElements[i]).find('.pro_sli_name').text();
					price = $(eyeElements[i]).find('.pro_sli_price').text();
					image = $(eyeElements[i]).find('.pro_sli_pic img').attr('src');
					const hadsellerInfo = await TopSellersModel.findOne({product_name: name, product_image: image}, '-_id');
					if(!hadsellerInfo) {
						id += 1;
						await TopSellersModel.create({product_id: id, category: 'eyeglasses', brand, product_name: name, price, product_image: image})
					}
				}
				const productData = await TopSellersModel.find({}, '-_id');
				res.send({
					status: 1,
					data: productData
				})
			} catch (err) {
				console.log('Error', err)
				throw new Error(err)
			}
		});
	}
}

export default new TopSellers()